import { defineStore } from 'pinia'
import { ref } from 'vue'
import { type User } from '@/types/user'
import type { PersistenceOptions } from 'pinia-plugin-persistedstate'
export const useUserStore = defineStore(
  'user',
  () => {
    const Authorization = ref<string | null>()
    const user = ref<User>({
      id: '',
      avatar: '',
      intro: '',
      nickName: '',
      sex: '',
      phone: '',
      province: '',
      city: '',
    })

    // 设置token
    function setToken(token: string) {
      Authorization.value = token
    }
    // 设置用户信息
    function setUser(newUser: User) {
      user.value = newUser
    }

    // 清空用户信息
    function clearUser() {
      user.value = {
        id: '',
        avatar: '',
        intro: '',
        nickName: '',
        sex: '',
        phone: '',
        province: '',
        city: '',
      }
    }
    // 清空token
    function clearToken() {
      Authorization.value = null
    }
    return { user, Authorization, setToken, setUser, clearUser, clearToken }
  },
  {
    persist: {
      key: 'userStore',
      paths: ['Authorization', 'user'],
      storage: window.localStorage,
    } as PersistenceOptions,
  },
)
